/* Timeslice.c */

#define _GNU_SOURCE

#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <time.h>
#include "loop.h"

int diff(struct timespec start, struct timespec end) {
    int sec = end.tv_sec - start.tv_sec ;
    int nsec = end.tv_nsec - start.tv_nsec ;
    if( nsec < 0 ) {
        return (sec-1) * 1E3 + (nsec+1E9) / 1E6;
    } else {
        return sec * 1E3 + nsec / 1E6;
    }
}

#define N 100

int main(int argc, char *argv[]) {
    int i;
    cpu_set_t cpuset;
    int t[N];
    struct timespec p, q;

    CPU_ZERO(&cpuset);
    CPU_SET(1, &cpuset);
    sched_setaffinity(getpid(), sizeof(cpu_set_t), &cpuset);
    clock_gettime(CLOCK_REALTIME, &p);
    loop(100);
    clock_gettime(CLOCK_REALTIME, &q);

    printf("cpu=%d ms=%d\n", sched_getcpu(), diff(p, q));
    fflush(stdout);

    for( i = 0; i < N; i++ ) {
        clock_gettime(CLOCK_REALTIME, &p);
        loop(10) ;
        clock_gettime(CLOCK_REALTIME, &q);
        t[i] = diff( p, q );
    }
    for( i = 0; i < N; i++ ) {
        printf("%d\n", t[i] );
    }
    return 0;
}

/*  Please note that the checks on the return value of the system calls
    have been omitted to avoid cluttering the code. However, system calls
    can and will fail, in which case the results are unpredictable. */
